package com.wei.demo10;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author cosmoswei
 */
public class CompletableFutureTest {
    public static Integer calc(Integer para) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }
        return para * para;
    }

    public static Integer calc2(Integer para) {

        return para / 0;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        final CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> calc(12));
        final CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> calc(13));

        System.out.println(future.get());


        CompletableFuture<Void> future1 = CompletableFuture.supplyAsync(() -> calc(20))
//                .thenCompose((i) -> CompletableFuture.supplyAsync(() -> calc(i)))
                .thenApply((i) -> Integer.toString(i))
                .thenApply((str) -> "\"" + str + "\"")
                .thenAccept(System.out::println);
        future1.get();

        CompletableFuture<Void> future2 = CompletableFuture
                .supplyAsync(() -> calc2(20))
                .exceptionally(ex -> {
                    System.out.println(ex.toString());
                    return 0;
                })
                .thenApply((i) -> Integer.toString(i))
                .thenApply((str) -> "\"" + str + "\"")
                .thenAccept(System.out::println);
        future2.get();

        CompletableFuture<Void> future4 = future.thenCombine(future3, (i, j) -> (i + j))
                .thenApply((str) -> "\"" + str + "\"")
                .thenAccept(System.out::println);
        future4.get();
    }
}
